import { useEffect, useMemo, useRef, useState } from "react"
import { Button, Drawer, Form, Input, Select, Space, Tabs, message } from "antd"
import { TextWidget, getMessage } from "@inbiz/react"
import { InbizIcon } from "@inbiz/utils"
// import MultilingualInput from "@inbiz/basic/MultilingualInput"
import { editFormData } from "../server"

const EditDrawer = (props: any) => {
  const { visible, $visible, record, groupData, refresh, design, activeAppId, findDomain } = props
  // 当前tab的key
  const [active, $active] = useState<string>('1')
  // 修改后的数据
  const [editInfo, $editInfo] = useState<any>()
  // 分组数据
  const [groupList, $groupList] = useState<any[]>([])
  // 编辑保存loading
  const [saveLoading, $saveLoading] = useState<boolean>(false)
  const [form] = Form.useForm()
  const iframeRef: any = useRef()
  const timer: any = useRef()

  // 初始进1页面
  useEffect(() => {
    if (visible) {
      $active('1')
      form.setFieldsValue({
        group: record?.ParentId,
        name: record?.Name,
        key: record?.Route,
        remark: record?.Description
      })
    }
  }, [visible, record])

  // 组合分组数据
  useEffect(() => {
    const list: any[] = []
    groupData.map((i: any) => {
      list.push(i)
      if (i.Children?.length) {
        i.Children.map((v: any) => {
          list.push({ ...v, down: true, ParentName: i.Name })
        })
      }
    })
    $groupList(list)
  }, [groupData])

  // 调转表单设计页面
  const jumpSetup = () => {
    design?.(record)
  }

  // 确定修改
  const submit = () => {
    $saveLoading(true)
    form.validateFields().then((res: any) => {
      editFormData({
        outId: record.OutId,
        dataVersionId: record.DataVersionId,
        name: res.name?.trim?.(),
        description: res.remark,
        pageGroupOutId: res.group,
        appId: props?.activeAppId
      }).then((suc: any) => {
        if (suc?.OutId) {
          $editInfo({
            ...record,
            Name: res.name,
            Description: res.remark,
            ParentId: res.group
          })
          message.success(getMessage('FormManage.save_succ'))
        }
        $saveLoading(false)
      })
    }).catch(() => {
      $active('1')
      $saveLoading(false)
    })
  }

  // 抽屉头dom
  const renderTitle = () => {
    return <>
      <div className="form-manage-edit-drawer-header">
        <span><TextWidget>{editInfo?.Name || record?.Name}</TextWidget></span>
        <InbizIcon
          className="close-drawer"
          type="icon-ic-close-bold"
          onClick={() => {
            $visible(false)
            if (editInfo) {
              refresh?.(1)
            }
            $editInfo(undefined)
          }}
        />
      </div>
    </>
  }

  // tab头部操作按钮
  const extraBtns = useMemo(() => {
    return (
      <Space>
        <Button onClick={jumpSetup}>
          <InbizIcon type="icon-biaodansheji" />
          {/* 表单设计 */}
          <TextWidget>FormManage.form_setup</TextWidget>
        </Button>
        {
          active == '1' &&
          <Button type='primary' onClick={submit} loading={saveLoading}>
            <InbizIcon type="icon-baocun1" />
            {/* 保存 */}
            <TextWidget>FormManage.save</TextWidget>
          </Button>
        }
      </Space>
    )
  }, [saveLoading, jumpSetup, submit])


  // 设置iframe里面页面表单不能点击
  useEffect(() => {
    const find = () => {
      let a = iframeRef.current?.contentWindow?.document?.body?.querySelector?.('form')
      clearTimeout(timer.current)
      if (a) {
        a.style.pointerEvents = 'none'
      } else {
        timer.current = setTimeout(() => {
          find()
        }, 300)
      }
    }
    if (visible) {
      find()
    } else {
      clearTimeout(timer.current)
    }
  }, [visible])

  const domian = findDomain(activeAppId)
  const pathname = process.env.NODE_ENV == 'development' ? `/${domian}` : `/inbiz/web/${domian}`
  const version = record?.DataVersionId ? '?v=' + record.DataVersionId : ''
  return (
    <>
      <Drawer
        visible={visible}
        width={800}
        placement="right"
        closable={false}
        title={renderTitle()}
        className='form-manage-edit-drawer'
        destroyOnClose
      >
        <Tabs activeKey={active} onChange={e => $active(e)} tabBarExtraContent={extraBtns}>
          {/* 基本信息 */}
          <Tabs.TabPane tab={getMessage('FormManage.info')} key="1">
            <Form form={form} labelCol={{ span: 3 }}>
              {/* 所属分组 */}
              <Form.Item
                name='group'
                label={getMessage('FormManage.at_group')} // 所属分组
                rules={[{ required: true, message: getMessage('FormManage.at_group_quest') }]}
              >
                <Select
                  dropdownClassName='form-manage-select-group'
                  placeholder={getMessage('FormManage.please_sele')} // 请选择
                  showSearch
                  virtual={false}
                  optionFilterProp="label"
                  filterOption={(input, option) => {
                    if (typeof option?.title == 'string') {
                      return (option?.title ?? '')?.toLowerCase().includes(input.toLowerCase())
                    } else {
                      return false
                    }
                  }}
                >
                  {
                    groupList.map((item: any) => {
                      return (
                        <Select.Option
                          value={item.OutId}
                          key={item.OutId}
                          className={item.down ? 'form-group-down' : ''}
                          title={getMessage(item.Name)}
                        >
                          <TextWidget>{item.Name}</TextWidget>
                        </Select.Option>
                      )
                    })
                  }
                </Select>
              </Form.Item>
              {/* 表单名称 */}
              <Form.Item
                name='name'
                label={getMessage('FormManage.form_name')} // 表单名称
                required
                rules={[
                  ({ }) => ({
                    validator(_, value): any {
                      if (!value || value?.trim?.() == '') {
                        return Promise.reject(new Error(getMessage('FormManage.form_name_quest')))
                      } else if (value.length > 50) {
                        return Promise.reject(getMessage('FormManage.limit_group_length'))
                      } else if (/^[\u4E00-\u9FA5A-Za-z0-9\_\-\——\'\(\)\。\、\【\】\‘\’\“\”\《\》\……\（\）\s]+$/.test(value)) {
                        /* 暂时去掉对语言支持 */
                        // } else if (/^[\u4E00-\u9FA5A-Za-z0-9\_\-\——\'\(\)\。\、\【\】\‘\’\“\”\《\》\……\（\）\s]+$/.test(value.replace('.i18n', '').replace('{multilingual}', ''))) {
                        return Promise.resolve()
                      }
                      return Promise.reject(getMessage('FormManage.special_character'))
                    },
                  }),
                ]}
              >
                {/* 暂时去掉对语言支持 */}
                {/* <MultilingualInput
                  placeholder={getMessage('FormManage.please_input')}
                /> */}
                <Input
                  placeholder={getMessage('FormManage.please_input')}
                />
              </Form.Item>
              {/* 标识 */}
              <Form.Item
                name='key'
                label={getMessage('FormManage.key')}
                rules={[
                  { required: true, message: getMessage('FormManage.key_quest') },
                  {
                    pattern: /^[a-zA-Z0-9_-]*$/,
                    message: getMessage('FormManage.key_check'),
                  },
                  {
                    pattern: /^.{2,50}$/,
                    message: getMessage('FormManage.key_long'),
                  }
                ]}
              >
                <Input placeholder={getMessage('FormManage.please_input')} disabled />
              </Form.Item>
              {/* 描述 */}
              <Form.Item name='remark' label={getMessage('FormManage.form_remark')}>
                <Input.TextArea placeholder={getMessage('FormManage.please_input')} />
              </Form.Item>
            </Form>
          </Tabs.TabPane>
          {/* 表单详情 */}
          <Tabs.TabPane tab={getMessage('FormManage.form_info')} key="2" forceRender>
            <iframe
              ref={iframeRef}
              className="form-preview"
              src={`${location.origin}${pathname}${version}#/form/${record?.Route}`}
            ></iframe>
          </Tabs.TabPane>
        </Tabs>
      </Drawer>
    </>
  )
}

export default EditDrawer